import { useEffect, useState, useRef } from 'react';
import { message } from 'antd';
import { ProFormText, ModalForm, ProFormSwitch, ProFormSelect } from '@ant-design/pro-components';
import { isLocal, isSuccess } from '@/utils';
import { eidtPasswrodApi } from '@/api';

export default function EidtPasswrod({ open, setOpen, formData, reload }: any) {
  const formRef: any = useRef('');
  console.log('formData: ', formData);

  useEffect(() => {
    if (open) initData();
  }, [open]);

  // 初始化数据
  const initData = () => {
    formRef?.current?.setFieldsValue(formData);
    if (isLocal()) {
      formRef?.current?.setFieldsValue({
        password: '1234567',
        passwordRepeat: '1234567',
      });
    }
  };

  // 提交
  const submit = async () => {
    let val = await formRef?.current?.validateFieldsReturnFormatValue();
    console.log('格式化后的表单数据: ', val);
    // 新增、编辑
    let params: any = {
      ...formData,
      ...val,
    };
    // 重复密码校验
    if (params.password !== params.passwordRepeat) {
      message.error('两次密码输入不一致');
      return;
    }
    console.log('params: ', params);
    let res: any = await eidtPasswrodApi(params);
    if (!isSuccess(res)) return;
    message.success('成功');
    reload();
    setOpen(false);
  };

  return (
    <ModalForm
      title="修改密码"
      formRef={formRef}
      open={open}
      layout="horizontal"
      onFinish={submit}
      onOpenChange={setOpen}
      labelCol={{ span: 4 }}
    >
      <br />
      <ProFormText name="name" label="账号" placeholder="请输入" disabled={true} />
      <ProFormText name="password" label="密码" placeholder="请输入" rules={[{ required: true }]} />
      <ProFormText
        name="passwordRepeat"
        label="重复密码"
        placeholder="请输入"
        rules={[{ required: true }]}
      />
    </ModalForm>
  );
}
